import { addSysDictType, updateSysDictType } from "@/api/sys/sysDict";
import { useAppDispatch, useAppSelector } from "@/store";
import {
  get_sys_dict_type_tree,
  select_is_show_dict_type_modal,
  set_is_show_dict_type_modal,
} from "@/store/slice/SysDict";

import { Form, Input, InputNumber, Modal, message } from "antd";
const { TextArea } = Input;

function DictTypeModal() {
  const [formRef] = Form.useForm();
  const dispatch = useAppDispatch();
  const is_show_data = useAppSelector(select_is_show_dict_type_modal);
  if (is_show_data.show && is_show_data.mode === 2) {
    formRef.setFieldsValue(is_show_data.data);
  }

  function handleOk() {
    formRef
      .validateFields()
      .then(async (values) => {
        // 表单校验通过，执行提交逻辑
        const res =
          is_show_data.mode === 1
            ? await addSysDictType(values)
            : await updateSysDictType({ ...values, id: is_show_data.data.id });
        if (res) {
          message.open({
            type: "success",
            content: "新增成功!",
          });
          dispatch(get_sys_dict_type_tree());
          onCancel();
        } else {
          message.open({
            type: "error",
            content: "新增失败!",
          });
        }
      })
      .catch(() => {
        message.open({
          type: "warning",
          content: "请填写完整信息!",
        });
      })
      .finally(() => {});
  }
  function reset() {
    formRef.resetFields();
  }
  function onCancel() {
    reset();
    dispatch(
      set_is_show_dict_type_modal({
        show: false,
        title: "",
        mode: 1,
        data: {},
      })
    );
  }

  function onChange(value: any) {}
  return (
    <Modal
      title={is_show_data.title}
      open={is_show_data.show}
      onOk={handleOk}
      onCancel={onCancel}
    >
      <Form
        form={formRef}
        labelAlign="right"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 16 }}
        onValuesChange={onChange}
      >
        <Form.Item
          name="dictCode"
          label="类型编码"
          rules={[
            {
              required: true,
              message: "请输入类型编码",
            },
          ]}
        >
          <Input placeholder="请输入类型编码" allowClear />
        </Form.Item>
        <Form.Item
          name="dictName"
          label="类型名称"
          rules={[
            {
              required: true,
              message: "请输入类型名称",
            },
          ]}
        >
          <Input placeholder="类型名称" allowClear />
        </Form.Item>
        <Form.Item
          name="sort"
          label="排序号"
          initialValue={is_show_data.data?.sort || 999}
        >
          <InputNumber />
        </Form.Item>
        <Form.Item name="remark" label="描述" >
          <TextArea placeholder="描述" allowClear rows={4}/>
        </Form.Item>
      
      </Form>
    </Modal>
  );
}
export default DictTypeModal;
